package com.soup.common.module.sys.service.impl;

import com.google.common.collect.ImmutableMap;
import com.soup.common.config.JwtProperties;
import com.soup.common.constant.CommonConstant;
import com.soup.common.constant.LoginContext;
import com.soup.common.service.BaseServiceImpl;
import com.soup.common.service.CacheService;
import com.soup.common.utils.PinyinUtil;
import com.soup.common.utils.RequestContextHolderUtil;
import com.soup.common.exception.sys.PwdErrorException;
import com.soup.common.module.sys.data.AuthResponse;
import com.soup.common.module.sys.data.SignInRequest;
import com.soup.common.module.sys.entity.User;
import com.soup.common.module.sys.mapper.UserMapper;
import com.soup.common.module.sys.service.JwtTokenService;
import com.soup.common.module.sys.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * sys service
 *
 * @author zhaoyi
 */
@Service
@Slf4j
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {

    @Autowired
    private JwtTokenService jwtTokenService;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private JwtProperties jwtProperties;

    @Value("${user.defaultPwd}")
    private String defaultPwd;

    @Override
    public AuthResponse login(SignInRequest signIn) {
        User user = userMapper.selectByLoginName(signIn.getLoginName());
        checkUser(user);

        if (StringUtils.equals(signIn.getPassword(), user.getPassword())) {
            // 登陆成功，生成token
            String randomKey = jwtTokenService.getRandomKey();
            String token = jwtTokenService.generateToken(user.getId().toString(), randomKey);

            cacheService.set(CommonConstant.TOKEN_CACHE, token, token);
            LoginContext.LOGIN_USER.set(user);

            return new AuthResponse(token, randomKey);
        } else {
            throw new PwdErrorException();
        }
    }

    @Override
    public int countbyRoleId(Integer roleId) {
        return countByEqual(ImmutableMap.of("roleId", roleId.toString()));
    }

    @Override
    public void createSysUser(String name, String identity) {
        // 根据员工新建系统用户，默认密码为身份证后六位
        User user = new User();
        // 使用员工姓名拼音作为登录账号
        user.setLoginName(PinyinUtil.toPinyin(name));
        String password = defaultPwd;
        if (StringUtils.isNotEmpty(identity)) {
            int len = identity.length();
            // 使用身份证后6位作为管理员登录密码
            password = identity.substring(len - CommonConstant.NUM_6, len);
        }
        user.setPassword(password);
        user.setNickName(name);
        user.setUserStatus(CommonConstant.ENABLED);
        user.setGmtCreate(new Date());
        save(user);
    }

    @Override
    public void logout() {
        String token = RequestContextHolderUtil.getRequest().getHeader(jwtProperties.getHeader());
        cacheService.remove(CommonConstant.TOKEN_CACHE, token);
        LoginContext.LOGIN_USER.remove();
    }
}
